<?php


namespace app\admin\model;


use app\common\model\BaseModel;
use custom\Mongo;

class LoginLog extends BaseModel {

    static $setName = 'login_log';

    /**
     * 列表
     * @param $params
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public static function getList($params) {
        $mongo = Mongo::getInstance();
        //删除大于90天的数据
//        $where = ['itime' => ['$lt' => time() - 7776000]];
//        $limit = ['limit' => 0];
//        $mongo->deldoc($where, $limit, self::$setName);
        $filter = [];
        if (!empty($params['admin_name'])) {
            $filter = ['admin_name' => ['$eq' => (string)trim($params['admin_name'])]];
        }
        $page = (int)$params['page'];
        $long = (int)$params['long'];
        $sort = ['_id' => -1];
        $cursor = $mongo->page($filter, $page, $long, self::$setName, $sort);
        $data = $cursor['data'];
        if (empty($data)) {
            $result = [
                'page'    => 1,
                'pageNum' => 1,
                'count'   => 0,
                'data'    => [],
            ];
        } else {
            foreach ($data as $index => $item) {
                $data[$index]->itime = date('Y-m-d H:i:s', $item->itime);
            }
            $result = [
                'page'    => $cursor['page'],
                'pageNum' => $cursor['pageNum'],
                'count'   => $cursor['count'],
                'data'    => $data,
            ];
        }
        return $result;
    }

    /**
     * 登录日志
     * @return mixed
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public static function saveLoginLog($data){
        $mongo = Mongo::getInstance();
        $last = $mongo->select(self::$setName, [], ['limit' => 1, 'sort' => ['_id' => -1]]);
        if(empty($last)){
            $data['_id'] = (int)1;
        }else{
            $last = (array)$last[0];
            $data['_id'] = (int)($last['_id'] + 1);
        }
        return $mongo->add($data, self::$setName);
    }


}